<template>
  <div class="app-container">
    <div v-show="active === 1">
      <div class="searchform">
        <!-- 查询条件 -->
        <el-form ref="searchForm" :model="search" size="mini" label-width="90px">
          <el-row :gutter="6">
            <el-col :xs="24" :sm="8" :md="6">
              <el-form-item prop="question_type" label="问卷类型">
                <r-select v-model="search.question_type" type="9717" class="form-input" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="8" :md="6">
              <el-form-item prop="question_name" label="问卷名称">
                <el-input v-model="search.question_name" placeholder="问卷名称" clearable/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="8" :md="6">
              <el-form-item prop="publish" label="发布状态">
                <r-select v-model="search.publish" type="9712" class="form-input"/>
              </el-form-item>
            </el-col>
            <div style="text-align:right">
              <el-button type="primary" icon="el-icon-search" @click="searchHandle">查询
              </el-button>
              <el-button icon="el-icon-refresh" @click="resetForm('searchForm')">重置
              </el-button>
            </div>
          </el-row>
        </el-form>
      </div>
      <!-- 用户列表 -->
      <div class="table">
        <div class="tableHead">
          <div class="tabletitle">问卷维护</div>
          <div class="btnGroup">
            <el-button-group>
              <el-button type="primary" icon="el-icon-plus" @click="add">新增
              </el-button>
            </el-button-group>
          </div>
        </div>
        <BaseTable ref="table" @chaneg-size="changeSizeHandle" @chaneg-page="changePageHandle" @selection-change="handleSelectionChange">
          <el-table-column type="index" label="序号" min-width="50"/>
          <!--          <el-table-column type="selection" min-width="40"/>-->
          <el-table-column align="center" label="操作" min-width="80">
            <template slot-scope="scope">
              <el-tooltip class="item" content="明细" placement="bottom">
                <el-button type="text" style="font-size: 20px;" icon="el-icon-document" @click="detail(scope.row)"/>
              </el-tooltip>
              <el-tooltip class="item" content="编辑" placement="bottom">
                <el-button
                  type="text"
                  style="font-size: 20px;"
                  icon="el-icon-edit-outline"
                  @click="edit(scope.row)"/>
              </el-tooltip>
              <el-tooltip class="item" content="发布" placement="bottom">
                <el-button
                  v-if="scope.row.publish == '未发布'"
                  type="text"
                  style="font-size: 20px;"
                  icon="el-icon-check"
                  @click="publish(scope.row)"/>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="question_type" label="问卷类型"/>
          <el-table-column prop="question_name" label="问卷名称"/>
          <el-table-column prop="status" label="有效状态" />
          <el-table-column prop="publish" label="发布状态" />
          <el-table-column prop="publish_time" label="发布时间" />
        </BaseTable>
      </div>
    </div>
    <!-- 新增div -->
    <el-dialog v-dialogDrag :title="text" :visible.sync="dialogVisible" :close-on-click-modal="false" :before-close="cancel" :append-to-body="true" width="50%">
      <div class="elform">
        <el-form ref="form" :model="form" :rules="rules" size="mini" label-width="90px">
          <el-row :gutter="6">
            <el-col :xs="24" :sm="24" :md="12">
              <el-form-item prop="question_name" label="问卷名称">
                <el-input v-model="form.question_name" placeholder="问卷名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12">
              <el-form-item prop="question_type" label="问卷类型" >
                <r-select v-model="form.question_type" placeholder="问卷类型" type="9717" class="form-input" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24">
              <el-form-item prop="question_context" label="问卷说明">
                <el-input :rows="2" v-model="form.question_context" type="textarea" placeholder="问卷说明" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12">
              <el-form-item prop="item_type" label="题目类型" >
                <r-select v-model="form.item_type" placeholder="题目类型" type="9702" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12">
              <el-button type="primary" size="mini" @click="addItem(form.item_type)">添加题目</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="elform">
        <el-form
          ref="noticefrom"
          :model="form.wtlist"
          label-width="90px"
        >
          <transition-group>
            <div v-for="(item, index) in form.wtlist" :key="item.item_id">
              <div>
                <div>
                  <el-row :gutter="6">
                    <el-col :xs="24" :sm="24" :md="12">
                      <el-form-item :label="questionTypeFn(item.item_type)" >
                        <el-input v-model="item.item_title" placeholder="请输入内容"/>
                      </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12">
                      <!-- <el-button :disabled="item.item_type === 97021001 ? true:false" type="primary" @click="spanVisible = true">添加选项</el-button> -->
                      <el-button :disabled="item.item_type === 97021001 ? true:false" type="primary" @click="open(item)">添加选项</el-button>
                      <el-button type="primary" @click="deleteItem(item,index)">删除</el-button>
                    </el-col>
                  </el-row>
                </div>
                <!-- <el-dialog
                  :visible.sync="spanVisible"
                  title="输入选项"
                  width="40%">
                  <el-input v-model="item.optionName" placeholder="请输入选项内容"/>
                  <el-button @click="spanVisible = false">取 消</el-button>
                  <el-button type="primary" @click="addOption(item)">确 定</el-button>
                </el-dialog> -->
                <div v-for="(option, idx) in item.optionlist" :key="idx">
                  <div :class="{ lineColor: line === item.uuid }" style="left:60px" >
                    <el-row :gutter="6">
                      <el-col :xs="24" :sm="24" :md="12">
                        <el-form-item>
                          <el-radio v-if="item.item_type == 97021002" :label="option.option_name">{{ option.option_name }}</el-radio>
                          <el-checkbox v-if="item.item_type == 97021003" >{{ option.option_name }}</el-checkbox>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </div>
              <el-divider/>
            </div>

          </transition-group>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button type="text">
          <i class="el-icon-search magnifier" />
        </el-button>
        <el-button type="primary" @click="save()" >保 存</el-button>
        <el-button @click="cancel()">取 消</el-button>

        <!-- </span> -->
      </div>
    </el-dialog>
    <!-- 编辑div -->
    <el-dialog v-dialogDrag :title="text" :visible.sync="editdialogVisible" :close-on-click-modal="false" :before-close="cancel" :append-to-body="true" width="65%" >
      <div class="elform">
        <el-form ref="editform" :model="editform" :rules="rules" size="mini" label-width="90px">
          <el-row :gutter="4">
            <el-col :xs="24" :sm="24" :md="8">
              <el-form-item prop="question_name" label="问卷名称">
                <el-input v-model="editform.question_name" :disabled="way == 'detail' || editform.publish == '已发布' " placeholder="问卷名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="8">
              <el-form-item prop="question_type" label="问卷类型" >
                <r-select v-model="editform.question_type" :disabled="way == 'detail' || editform.publish == '已发布'" placeholder="问卷类型" type="9717" class="form-input" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="7">
              <el-form-item prop="status" label="是否有效" >
                <r-select v-model="editform.status" :disabled="way == 'detail'" placeholder="是否有效" type="1001" class="form-input" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24">
              <el-form-item prop="question_context" label="问卷说明">
                <el-input :rows="2" v-model="editform.question_context" :disabled="way == 'detail' || editform.publish == '已发布'" type="textarea" placeholder="问卷说明" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12">
              <el-form-item v-show="way == 'edit' && editform.publish == '未发布'" prop="item_type" label="题目类型" >
                <r-select v-model="editform.item_type" placeholder="题目类型" type="9702" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12">
              <el-button v-show="way == 'edit' && editform.publish == '未发布'" type="primary" size="mini" @click="editItem(editform.item_type)">添加题目</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="elform">
        <el-form
          ref="noticefrom"
          :model="wtlist"
          label-width="90px"
        >
          <transition-group>
            <div v-for="(item, index) in wtlist" :key="index">
              <div>
                <div>
                  <el-row :gutter="6">
                    <el-col :xs="24" :sm="24" :md="12">
                      <el-form-item :label="questionTypeFn(item.item_type)" >
                        <el-input :disabled="way == 'detail' || editform.publish == '已发布'" v-model="item.item_title" placeholder="请输入内容"/>
                      </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12">
                      <!-- <el-button :disabled="item.item_type === 97021001 ? true:false" type="primary" @click="spanVisible = true">添加选项</el-button> -->
                      <el-button v-show="way == 'edit' && editform.publish == '未发布'" :disabled="item.item_type === 97021001 ? true:false" type="primary" @click="editopen(item)">添加选项</el-button>
                      <el-button v-show="way == 'edit' && editform.publish == '未发布'" type="primary" @click="editDeleteItem(item,index)">删除</el-button>
                    </el-col>
                  </el-row>
                </div>
                <el-dialog
                  :visible.sync="spanVisible"
                  title="输入选项"
                  width="40%">
                  <el-input v-model="item.optionName" placeholder="请输入选项内容"/>
                  <el-button @click="spanVisible = false">取 消</el-button>
                  <el-button type="primary" @click="editOption(item)">确 定</el-button>
                </el-dialog>
                <div v-for="(option, idx) in item.optList" :key="idx">
                  <div :class="{ lineColor: line === item.uuid }" style="left:60px" >
                    <el-row :gutter="6">
                      <el-col :xs="24" :sm="24" :md="12">
                        <el-form-item>
                          <el-radio v-if="item.item_type == 97021002" :disabled="way == 'detail' || editform.publish == '已发布'" :label="option.option_name">{{ option.option_name }}</el-radio>
                          <el-checkbox v-if="item.item_type == 97021003" :disabled="way == 'detail' || editform.publish == '已发布'" >{{ option.option_name }}</el-checkbox>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </div>
              <el-divider/>
            </div>

          </transition-group>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button type="text">
          <i class="el-icon-search magnifier" />
        </el-button>
        <el-button v-show="way == 'edit'" type="primary" @click="editsave()" >保 存</el-button>
        <el-button v-show="way == 'edit'" @click="cancel()">取 消</el-button>
        <el-button v-show="way == 'detail'" @click="cancel()">返 回</el-button>

        <!-- </span> -->
      </div>
    </el-dialog>

    <!-- 弹框 -->

  </div>
</template>

<script>
import {
  stopById,
  startById
} from '@/api/admin/auth/gms/authManagement'
import {
  queryQuestionnaire,
  addQuestionnaire,
  editQuestionnaire,
  getInfoById,
  publish
} from '@/api/admin/auth/gms/questionnaire'
import Pagination from '@/components/Pagination'
import BaseTable from '@/components/BaseTable'
import BaseTableNoPage from '@/components/BaseTable/BaseTableNoPage'
import formMixins from '@/mixins/formMixins'
import rSelect from '@/components/Select/Select'
import filtercode from '@/components/Checkbox/filtercode'
import _ from 'lodash'
export default {
  name: 'QuestionnaireManage',
  components: {
    BaseTable,
    BaseTableNoPage,
    Pagination,
    rSelect,
    filtercode
  },
  mixins: [formMixins],
  data() {
    return {
      type: '',
      radio: [],
      line: '',
      active: 1,
      list: [],
      checkedList: [],
      load: false,
      page: {},
      multipleSelection: [],
      authSelection: [],
      ids: 0,
      way: '',
      text: '',
      rules: {
        question_name: [{
          required: true,
          message: '请填写名称',
          trigger: 'blur'
        }],
        question_type: [{
          required: true,
          message: '请选择类型',
          trigger: 'blur'
        }]
      },
      search: {
        limit: 10,
        pageNum: 1,
        question_type: '',
        question_name: '',
        status: '',
        publish: '',
        question_id: '',
        question_context: '',
        publish_time: ''
      },
      dialogEditVisible: false,
      dialogVisible: false,
      editdialogVisible: false,
      itemVisible: false,
      spanVisible: false,
      form: {
        question_id: '',
        question_name: '',
        question_type: '',
        status: '',
        publish: '',
        question_context: '',
        item_type: 97021002,
        wtlist: []
      },
      editform: {
        question_id: '',
        question_name: '',
        question_type: '',
        status: '',
        question_context: '',
        item_type: '',
        publish: ''
      },
      wtlist: [
        { item_id: '',
          item_title: '',
          item_type: '',
          optionName: '',
          optList: [{
            option_name: '',
            option_id: '',
            item_id: ''
          }]
        }
      ]
    }
  },
  computed() {
    // this.radio = ['备选项1', '备选项2']
  },
  watch: {
    '$route.params.employeeName'(val, oldval) {
      const employeeName = this.$route.params.employeeName
      if (employeeName) {
        this.search.employeeName = employeeName
        this.searchHandle()
      }
    }
  },
  mounted() {
    const employeeName = this.$route.params.employeeName
    if (employeeName) { this.search.employeeName = employeeName }
    this.searchHandle()
  },
  methods: {
    open(data) {
      this.$prompt('请输入选项内容', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        data.optionlist.push({
          option_name: value,
          option_id: this.createUidKey()
        })
        this.$message({
          type: 'success',
          message: '你添加的选项是: ' + value
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    editopen(data) {
      this.$prompt('请输入选项内容', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        data.optList.push({
          option_name: value,
          option_id: null
        })
        this.$message({
          type: 'success',
          message: '你添加的选项是: ' + value
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    questionTypeFn(data) {
      let st = ''
      switch (data) {
        case 97021001:
          st = '问答题'
          break
        case 97021002:
          st = '单选题'
          break
        case 97021003:
          st = '多选题'
          break
        default:
          st = ''
      }
      return st
    },
    createUidKey(key = '') {
      // 创建UID
      if (key !== '') {
        key += '-'
      }
      const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        const r = (Math.random() * 16) | 0
        const v = c == 'x' ? r : (r & 0x3) | 0x8
        return v.toString(16)
      })
      return key + uuid
    },
    // 查询
    searchHandle() {
      const table = this.$refs['table']
      const search = _.extend(this.search)
      table.wait()
      queryQuestionnaire(search).then(res => {
        table.complete().filData(res)
      }).catch(err => {
        table.complete()
      })
    },
    // 回显
    Check(data) {
      // this.$nextTick(() => {
      //   this.$refs.editform.resetFields()
      //   this.editform = data
      // })
      const id = data.question_id
      console.log('id' + id)

      getInfoById(id).then(item => {
        console.log(item)
        this.editform = item.infoList[0]
        this.wtlist = item.qsList
      })
        .catch(err => {
        })
      // getDealerTableList(id).then(res => {
      //   if(res[0].DEALER_ID!=null){
      //     this.dealerList = res;
      //    }
      // }).catch(err => {
      // });
      this.editform.question_id = id
      console.log('回显' + this.editform.question_id)
      this.itemVisible = 'true'
      // console.log('回显' + this.form.wtlist)
    },
    addItem(n) {
      this.itemVisible = 'true'
      this.form.wtlist.push({
        // uuid: this.createUidKey(),
        optionlist: [],
        optionName: null,
        item_id: this.createUidKey(),
        item_title: null,
        item_type: n

      })
    },
    editItem(n) {
      if (n == null) {
        this.$message({
          message: '请选择题目类型！',
          type: 'warning'
        })
      } else {
        this.itemVisible = 'true'
        this.wtlist.push({
        // uuid: this.createUidKey(),
          optList: [],
          optionName: null,
          item_id: null,
          item_title: null,
          item_type: n

        })
        this.$message({
          message: '成功添加一条题目！',
          type: 'success'
        })
      }
    },
    deleteItem(item, index) {
      this.form.wtlist.splice(index, 1)
    },
    editDeleteItem(item, index) {
      // console.log(this.editform.wtlist)
      this.wtlist.splice(index, 1)
    },
    addOption(item) {
      alert(item.item_id)
      this.spanVisible = false
      item.optionlist.push({
        option_name: item.optionName,
        option_id: this.createUidKey()
      })
    },
    editOption(item) {
      this.spanVisible = false
      item.optList.push({
        option_name: item.optionName,
        option_id: null
      })
    },
    // 新增
    add() {
      this.text = '问卷新增'
      this.way = 'add'
      this.dialogVisible = true
      this.form.wtlist = []
      this.$nextTick(() => {
        this.$refs.form.resetFields()
      })
    },
    // 编辑
    edit(data) {
      console.log('状态' + data.status)
      this.text = '问卷编辑'
      this.way = 'edit'
      this.editdialogVisible = true
      this.Check(data)
    },
    // 明细
    detail(data) {
      console.log('状态' + data.status)
      this.text = '问卷明细'
      this.way = 'detail'
      this.editdialogVisible = true
      this.Check(data)
    },
    // 新增保存
    save() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const items = JSON.parse(JSON.stringify(this.form.wtlist))
          console.log('fffff', items[0])
          console.log('fffff', items[0].optionlist)
          const list = []
          for (var i = 0; i < items.length; i++) {
            list.push(items[i].optionlist)
          }
          console.log('llll', list[0])

          const params = {
            questionName: this.form.question_name,
            questionType: this.form.question_type,
            questionContext: this.form.question_context,
            questionItemDTOS: this.form.wtlist,
            questionOptionDTOS: list[0]
          }
          console.log('addparams' + params)
          if (this.way === 'add') {
            addQuestionnaire(params).then(res => {
              this.$message({
                type: 'success',
                message: '问卷保存成功!'
              })
              this.cancel()
              this.dialogVisible = false
              this.searchHandle()
            }).catch(err => {
              this.$message({
                type: 'error',
                message: err.response.data.errorMsg
              })
            })
          }
        }
      })
    },
    editsave() {
      this.$refs['editform'].validate(valid => {
        if (valid) {
          if (this.editform.question_type == '乘车试驾问卷') {
            this.editform.question_type = '97171001'
          } else if (this.editform.question_type == '交车满意度问卷') {
            this.editform.question_type = '97171002'
          }
          if (this.editform.status == '有效') {
            this.editform.status = '10011001'
          } else if (this.editform.status == '无效') {
            this.editform.status = '10011002'
          }
          if (this.editform.publish == '已发布') {
            this.editform.publish = '97121001'
          } else if (this.editform.publish == '未发布') {
            this.editform.publish = '97121002'
          }
          console.log('editform' + this.editform)
          const editparams = {
            questionID: this.editform.question_id,
            questionName: this.editform.question_name,
            questionType: this.editform.question_type,
            questionContext: this.editform.question_context,
            questionStatus: this.editform.status,
            questionItemDTOS: this.wtlist,
            publish: this.editform.publish

          }
          console.log('editparams' + this.wtlist)

          if (this.way === 'edit') {
            editQuestionnaire(editparams).then(res => {
              this.$message({
                type: 'success',
                message: '问卷保存成功!'
              })
              this.cancel()
              this.dialogVisible = false
              this.searchHandle()
            }).catch(err => {
              this.$message({
                type: 'error',
                message: err.response.data.errorMsg
              })
            })
          }
        }
      })
    },
    cancel() {
      this.text = ''
      this.way = ''
      this.dialogVisible = false
      this.editdialogVisible = false
    },
    // 发布
    publish(data) {
      publish(data).then(res => {
        this.$message({
          type: 'success',
          message: '发布成功！'
        })
        this.searchHandle()
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '发布失败！'
        })
      })
    },
    table2Delete(index, row) {
      const table2 = this.$refs.table2
      const tableData = this.$refs.table2.getData()
      let isDefalut = false
      if (tableData[index].IS_DEFAULT === 10041001 && tableData.length > 1) {
        isDefalut = true
      }
      table2.delete(index)

      if (isDefalut) {
        const tableData2 = this.$refs.table2.getData()
        tableData2[0].IS_DEFAULT = 10041001
      }
    },
    tableDefault(index, row) {
      const table2 = this.$refs.table2.getData()
      table2.forEach((res, idx) => {
        if (idx === index) {
          res.IS_DEFAULT = 10041001
        } else {
          res.IS_DEFAULT = 10041002
        }
      })
    },
    // 禁用
    disableStatus(data) {
      console.dir(data)
      const id = data.EMP_ID
      this.$confirm('是否禁用', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '禁用成功!'
          })
          stopById(id).then(res => {
            this.searchHandle()
          })
        })
        .catch(err => {
          this.$message({
            type: 'info',
            message: '已取消禁用'
          })
        })
    },
    // 启用
    enableStatus(data) {
      const id = data.EMP_ID
      this.$confirm('是否启用', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '启用成功!'
          })
          startById(id).then(res => {
            this.searchHandle()
          })
        })
        .catch(err => {
          this.$message({
            type: 'info',
            message: '已取消启用'
          })
        })
    },
    // 查询列表选择
    handleSelectionChange(val) {
      this.authSelection = val
    },
    // 角色选择分页
    handleSizeChange(size) {
      this.roleSearch.limit = size
      this.searchRole()
    },
    handleCurrentChange(page) {
      this.roleSearch.pageNum = page
      this.searchRole()
    },

    // 返回清空列表
    clear() {
      const table1 = this.$refs['table1']
      table1.filData(this.returnList)
      const table2 = this.$refs['table2']
      table2.filData(this.returnList)
      this.ids = 0
      this.type = 0

      this.active = 1
    }
  }
}

</script>

<style scoped>
  el-upload-upload {
    height:20px;
    width:100%;
  }

  .new-order-wrapper {
    padding: 10px 20px;
  }

  .new-order-wrapper .el-step__title {
    font-size: 14px;
  }

  .row-line {
    width: 100%;
  }

  .bm-view {
    width: 100%;
    height: 300px;
  }
  .redItem .el-form-item__label{
    color: indianred;
  }

.input1 {
    min-height: 30px;
    margin: 0px;
    width: 50px;
}

</style>
